require "Board"

class Position < ActiveRecord::Base
	belongs_to :game
	#has_one :parent,
	 # :class_name => "Position",
	 # :foreign_key => :parent_id
	has_one :entry_move,
		:class_name => "Move",
		:foreign_key => :ending_position_id,
		:dependent => true
	has_many :exit_moves,
		:class_name => "Move",
		:foreign_key => :starting_position_id,
		:dependent => true
		
	acts_as_tree

	class IllegalMove < Exception
		def initialize(move)
			super("illegal move from '#{move.starting_position_coordinates}' to '#{move.ending_position_coordinates}'")
		end
	end
	
	def duplicate
		p = Position.new
		
		self.attributes.each do |attr, val|
			if /^\w\d$/.match(attr) || /_moved$/.match(attr) then
				p.send("#{attr}=", val)
			end
 		end
 		p.game = self.game
 		
		p
	end

	def make_move(move_string)
		move = Move.new
		move.parse_move_string(move_string)

		$TRACE.debug 5, "before move"
		begin
		new_position = Chess_Board.new(self).move(move)
		rescue Exception => e
			$TRACE.debug 5, "move exception: #{e.message}"
			$TRACE.debug 5, e.backtrace.join("\n")
			raise e
		end
=begin
		# see if move is legal
		new_position = self.duplicate

		$TRACE.debug 5, "starting_position coord = #{move.starting_position_coordinates} val = #{new_position.send(move.starting_position_coordinates)}"
		$TRACE.debug 5, "end_position coord = #{move.ending_position_coordinates} val = #{new_position.send(move.ending_position_coordinates)}"
		#puts "new_position = #{new_position.inspect}"
		piece = new_position.send(move.starting_position_coordinates)
		new_position.send("#{move.starting_position_coordinates}=", " ")
		new_position.send("#{move.ending_position_coordinates}=", piece)
		new_position.parent = self
		new_position.save
		$TRACE.debug 5, "starting_position coord = #{move.starting_position_coordinates} val = #{new_position.send(move.starting_position_coordinates)}"
		$TRACE.debug 5, "end_position coord = #{move.ending_position_coordinates} val = #{new_position.send(move.ending_position_coordinates)}"
		#puts "new_position = #{new_position.inspect}"
=end
		new_position.parent = self
		new_position.move = move.detail
		new_position.save

		move.starting_position = self
		move.ending_position = new_position
		move.save

		new_position
	end

	def legal_moves(position_string)
		piece = self.send(position_string)
		
	end
end
